package com.ruoyi.pos.service.impl.device;

import com.ruoyi.pos.domain.device.PosDevice;
import com.ruoyi.pos.domain.dto.device.request.DeviceQueryRequest;
import com.ruoyi.pos.domain.dto.device.request.DeviceHeartbeatRequest;
import com.ruoyi.pos.domain.dto.device.request.DeviceAutoRegisterRequest;
import com.ruoyi.pos.domain.dto.device.request.DeviceDebugCommandRequest;
import com.ruoyi.pos.domain.dto.device.response.DeviceResponse;
import com.ruoyi.pos.domain.dto.device.response.DeviceHeartbeatResponse;
import com.ruoyi.pos.domain.dto.device.response.DeviceAutoRegisterResponse;
import com.ruoyi.pos.domain.dto.device.response.DeviceDebugLogResponse;
import com.ruoyi.pos.domain.dto.common.response.BasePageResponse;
import com.ruoyi.pos.mapper.device.PosDeviceMapper;
import com.ruoyi.pos.service.device.IPosDeviceService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * POS设备Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-30
 */
@Service
@Transactional(transactionManager = "posTransactionManager")
public class PosDeviceServiceImpl implements IPosDeviceService {

    private static final Logger logger = LoggerFactory.getLogger(PosDeviceServiceImpl.class);

    @Autowired
    private PosDeviceMapper posDeviceMapper;

    // ==================== 实现接口方法 ====================
    
    @Override
    public PosDevice selectPosDeviceByDeviceId(Long deviceId) {
        return posDeviceMapper.selectPosDeviceById(deviceId);
    }

    @Override
    public PosDevice selectPosDeviceByCode(String deviceCode) {
        return posDeviceMapper.selectPosDeviceByCode(deviceCode);
    }

    @Override
    public List<PosDevice> selectPosDeviceList(PosDevice posDevice) {
        return posDeviceMapper.selectPosDeviceList(posDevice);
    }

    @Override
    public int insertPosDevice(PosDevice posDevice) {
        posDevice.setCreateTime(new Date());
        posDevice.setUpdateTime(new Date());
        // 设置默认状态
        if (posDevice.getStatus() == null) {
            posDevice.setStatus("1"); // 默认正常
        }
        return posDeviceMapper.insertPosDevice(posDevice);
    }

    @Override
    public int updatePosDevice(PosDevice posDevice) {
        posDevice.setUpdateTime(new Date());
        return posDeviceMapper.updatePosDevice(posDevice);
    }

    @Override
    public int deletePosDeviceByDeviceIds(Long[] deviceIds) {
        return posDeviceMapper.deletePosDeviceByDeviceIds(deviceIds);
    }

    @Override
    public int deletePosDeviceByDeviceId(Long deviceId) {
        return posDeviceMapper.deletePosDeviceByDeviceId(deviceId);
    }

    @Override
    public int updatePosDeviceStatus(Long deviceId, String status) {
        try {
            PosDevice device = new PosDevice();
            device.setDeviceId(deviceId);
            device.setStatus(status);
            device.setUpdateTime(new Date());
            
            return posDeviceMapper.updatePosDevice(device);
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public int updateDeviceConfig(Long deviceId, Object config) {
        try {
            PosDevice device = new PosDevice();
            device.setDeviceId(deviceId);
            device.setUpdateTime(new Date());
            // 将配置信息存储在reserved1字段中（JSON格式）
            if (config != null) {
                device.setReserved1(config.toString());
            }
            return posDeviceMapper.updatePosDevice(device);
        } catch (Exception e) {
            logger.error("更新设备配置失败", e);
            return 0;
        }
    }

    @Override
    public DeviceAutoRegisterResponse autoRegisterDevice(DeviceAutoRegisterRequest request) {
        DeviceAutoRegisterResponse response = new DeviceAutoRegisterResponse();
        
        try {
            // 1. 检查设备是否已存在（通过Android ID）
            PosDevice existingDevice = new PosDevice();
            existingDevice.setAndroidId(request.getAndroidId());
            List<PosDevice> devices = posDeviceMapper.selectPosDeviceList(existingDevice);
            
            if (devices != null && !devices.isEmpty()) {
                // 设备已存在，更新设备信息
                PosDevice device = devices.get(0);
                device.setIpAddress(request.getIpAddress());
                device.setAppVersion(request.getAppVersion());
                device.setSystemVersion(request.getSystemVersion());
                device.setLastOnlineTime(new Date());
                device.setUpdateTime(new Date());
                
                posDeviceMapper.updatePosDevice(device);
                
                response.setSuccess(true);
                response.setDeviceId(device.getDeviceId());
                response.setDeviceCode(device.getDeviceCode());
                response.setMessage("设备已存在，信息已更新");
            } else {
                // 新设备，创建设备记录
                PosDevice newDevice = new PosDevice();
                // 生成设备编号：DEV + 时间戳后8位
                String deviceCode = "DEV" + System.currentTimeMillis() % 100000000L;
                newDevice.setDeviceCode(deviceCode);
                newDevice.setDeviceName(request.getDeviceName() != null ? request.getDeviceName() : "自动注册设备");
                newDevice.setAndroidId(request.getAndroidId());
                newDevice.setIpAddress(request.getIpAddress());
                newDevice.setAppVersion(request.getAppVersion());
                newDevice.setSystemVersion(request.getSystemVersion());
                newDevice.setStatus("1"); // 正常状态
                newDevice.setLastOnlineTime(new Date());
                newDevice.setCreateTime(new Date());
                newDevice.setUpdateTime(new Date());
                newDevice.setRemark("自动注册");
                
                int result = posDeviceMapper.insertPosDevice(newDevice);
                
                if (result > 0) {
                    response.setSuccess(true);
                    response.setDeviceId(newDevice.getDeviceId());
                    response.setDeviceCode(newDevice.getDeviceCode());
                    response.setMessage("设备注册成功");
                } else {
                    response.setSuccess(false);
                    response.setMessage("设备注册失败");
                }
            }
        } catch (Exception e) {
            logger.error("设备自动注册失败", e);
            response.setSuccess(false);
            response.setMessage("设备注册异常：" + e.getMessage());
        }
        
        return response;
    }

    @Override
    public Object getDeviceHeartbeat(Long deviceId) {
        DeviceHeartbeatResponse response = new DeviceHeartbeatResponse();
        PosDevice device = selectPosDeviceByDeviceId(deviceId);
        if (device != null) {
            response.setDeviceId(device.getDeviceId());
            response.setDeviceCode(device.getDeviceCode());
            response.setLastOnlineTime(device.getLastOnlineTime());
            response.setStatus(device.getStatus());
        }
        return response;
    }

    @Override
    public List<DeviceDebugLogResponse> getDeviceDebugLogs(Long deviceId, DeviceDebugLogResponse filter) {
        // 调试日志功能：从reserved2字段获取日志记录（JSON格式）
        // 注：实际生产环境中，建议使用独立的调试日志表
        List<DeviceDebugLogResponse> logs = new ArrayList<>();
        try {
            PosDevice device = selectPosDeviceByDeviceId(deviceId);
            if (device != null && device.getReserved2() != null) {
                // 这里可以解析JSON格式的日志数据
                // 示例：返回空列表，实际需要根据业务需求实现
                logger.info("获取设备 {} 的调试日志", deviceId);
            }
        } catch (Exception e) {
            logger.error("获取设备调试日志失败", e);
        }
        return logs;
    }

    @Override
    public int clearDeviceDebugLogs(Long deviceId) {
        // 清除调试日志：清空reserved2字段
        try {
            PosDevice device = new PosDevice();
            device.setDeviceId(deviceId);
            device.setReserved2(null);
            device.setUpdateTime(new Date());
            return posDeviceMapper.updatePosDevice(device);
        } catch (Exception e) {
            logger.error("清除设备调试日志失败", e);
            return 0;
        }
    }

    @Override
    public boolean sendDebugCommand(DeviceDebugCommandRequest request) {
        // 发送调试命令：通过WebSocket发送命令到设备
        // 注：实际实现需要集成DeviceDebugWebSocketHandler
        try {
            logger.info("向设备 {} 发送调试命令: {}", request.getDeviceId(), request.getCommand());
            // 将命令信息记录到reserved3字段（可选）
            PosDevice device = new PosDevice();
            device.setDeviceId(request.getDeviceId());
            device.setReserved3("Last command: " + request.getCommand() + " at " + new Date());
            device.setUpdateTime(new Date());
            posDeviceMapper.updatePosDevice(device);
            return true;
        } catch (Exception e) {
            logger.error("发送调试命令失败", e);
            return false;
        }
    }
}
